import React, { useEffect, useState } from 'react'
import { Card, Tree, Input, Form, Button, Table, Row, message, Col, Tag, Space, Modal } from 'antd'
import { RightOutlined, ExclamationCircleOutlined, DownOutlined, CaretRightOutlined, DeleteOutlined, EditOutlined, SettingFilled } from '@ant-design/icons'
import { getRolesListAPI, addRoleAPI, deleteRoleAPI, editRoleAPI, setRoleRights, deleteRoleRights } from '../../app/roles'
import { getAllRights } from '../../app/rights'
import './index.less'

const { confirm } = Modal
export default function Rights () {
    // 增加角色表单实例
    const [addRoleForm] = Form.useForm()

    // 编辑角色表单实例
    const [editRoleForm] = Form.useForm()

    // 设置初始角色列表数据
    const [rolesList, setRolesList] = useState([])

    // 编辑角色初始值
    const [editRole, setEditRole] = useState({})

    // 显示角色授权模态框
    const [isDispatchRoleRightsVisible, setIsDispatchRoleRightsVisible] = useState(false)

    // 权限分配之所有权限
    const [treeAllRightsData, setTreeAllRightsData] = useState([])

    // 树形结构默认选中的 key
    const [defaultKeys, setDefaultKeys] = useState([])

    // 树形结构选中的所有选中权限id
    const [checkRightsId, setCheckRightsId] = useState('')

    // 权限分配的角色ID
    const [roleID, setRoleID] = useState(0)

    // 显示增加角色模态框
    const [isAddRoleVisible, setIsAddRoleVisible] = useState(false)

    // 显示编辑角色模态框
    const [isEditRoleVisible, setIsEditRoleVisible] = useState(false)


    // 发请求，获取角色列表数据
    const getRolesList = async () => {
        const { data, meta } = await getRolesListAPI()
        if(meta.status !== 200) return message.error('获取角色列表数据失败')
        data.forEach((item, index) => item.index = index)
        setRolesList(data)
    }

    // 设置树形数据结构
    const changeTreeData = data => {
        return data.map(item => {
            if(item.children?.length > 0) {
                return {key: item.id + '', title: item.authName, children: changeTreeData(item.children) }
            }
            return {key: item.id + '', title: item.authName, children: []}
        })
    }

    // 拿到 tab 表格中一行数据的所有权限id
    const getAllRightsId = data => {
        return data.map(item => {
            if(item.children?.length > 0) {
               return getAllRightsId(item.children).join(',')
            }
            return item.id
        })
    }
    // 发请求，获取所有权限树形数据
    const getAllRightsData = async () => {
        const { data, meta } = await getAllRights('tree')
        if(meta.status !== 200) return message.error('获取权限列表失败')
        setTreeAllRightsData(changeTreeData(data))
    }

    // 增加角色校验规则
    const addRoleRules = {
        roleName:[
            { required: true, message: '角色名称不能为空' },
            { pattern:/^\S.*\S$|(^\S{0,1}\S$)/, message:'角色名称前后不能带有空格' }
        ],
        roleDesc:[
            { pattern:/^\S.*\S$|(^\S{0,1}\S$)/, message:'角色名称前后不能带有空格' }
        ]
    }
    // 获取角色列表数据
    useEffect(() => {
        getRolesList()
    }, [])

    // 标签关闭
    const tagsColse = async (e, roleId, rightId ) => {
        // console.log(roleId)
        // console.log(rightId)
        e.preventDefault()
        const { meta } = await deleteRoleRights(roleId, rightId)
        if(meta.status !== 200) return message.error('取消权限失败')
        getRolesList()
      }

    // 配置展开内容
    const expandedRowRender = (record) => {
        const { children } = record
        const component =
        <>
        {
            children.map(item => {
            return <Row key={item.id} align="middle" >
                <Col span={8}>
                    <Tag color="processing">{item.authName}</Tag>
                    <CaretRightOutlined />
                </Col>
                <Col span={16}>
                    {
                        item.children.map(obj => {
                            return <Row key={obj.id} align="middle">
                                <Col span={8}>
                                    <Tag color="success">{obj.authName}</Tag>
                                    <CaretRightOutlined />
                                </Col>
                                <Col span={16}>
                                {
                                    obj.children.map(item => {
                                      return <Tag key={item.id} closable  onClose={e => {tagsColse(e, record.id, item.id)}} color="warning">{item.authName}</Tag>
                                    })
                                }
                                </Col>
                            </Row>
                        })
                    }
                </Col>
            </Row>
            })
        }
        </>
        return component
    }

    // 展开图标自定义配置
    const expandIcon = ({ expanded, onExpand, record }) => {
        const component =  expanded ? (<DownOutlined onClick={e => onExpand(record, e)} />) : (<RightOutlined onClick={e => onExpand(record, e)} />)
        return component
    }

    // 新增角色
    const addRole = () => {
        addRoleForm.resetFields()
        setIsAddRoleVisible(true)
    }
    // 确认增加角色
    const handleAddRole = () => {
        addRoleForm.validateFields()
        .then(async values => {
            const { meta } = await addRoleAPI(values)
            if(meta.status !== 201) return message.error('添加角色失败')
            message.success('添加角色成功')
            getRolesList()
            setIsAddRoleVisible(false)
        })
        .catch(() => {
            message.error('请规范填写内容')
        })
    }
    // 取消增加角色
    const handleCancelAddRole = () => {
        setIsAddRoleVisible(false)
    }

    // 点击编辑按钮，弹出编辑模态框
    const onEditRole = (record) => {
        editRoleForm.resetFields()
        const { id, roleName, roleDesc } = record
        setEditRole({id, roleName, roleDesc})
        setIsEditRoleVisible(true)
        editRoleForm.setFieldsValue({id, roleName, roleDesc})
    }

    // 确认编辑角色
    const handleEditRole = () => {
        editRoleForm.validateFields()
        .then(async values => {
            const { meta } = await editRoleAPI({ ...editRole, ...values })
            if(meta.status !== 200) return message.error('编辑角色失败')
            message.success('编辑角色成功')
            setIsEditRoleVisible(false)
            getRolesList()
        })
        .catch(() => {
            message.error('请规范填写内容')
        })
    }
    // 取消编辑角色
    const handleCancelEditRole = () => {
        setIsEditRoleVisible(false)
    }

    // 删除角色
    const onDeleteRole = id => {
        confirm({
            title: '是否永久删除该角色',
            icon: <ExclamationCircleOutlined />,
            okText: '确认',
            cancelText: '取消',
            async onOk() {
                const { meta } = await deleteRoleAPI(id)
                if(meta.status !== 200) return message.error('删除角色失败')
                message.error('删除角色成功')
                getRolesList()
              }
          })
    }

    // 将选中的所有key保存下来
    const onCheckRoles = (checkedKeys, e) => {
    const checkKeys = checkedKeys.concat(e.halfCheckedKeys)
    // console.log(checkKeys)
    setCheckRightsId(checkKeys.join(','))
    }

    // 角色授权 这是一个大坑 getAllRightsData() 调用是异步的
    // 会先执行setIsDispatchRoleRightsVisible(true) 所以是[],后面数据更新默认的不生效
    const onSetRoleRight = async record => {
        // console.log(record)
        setRoleID(record.id)
        const allId = getAllRightsId(record.children)
        const allIdRes = allId.length ? allId.map(item => item.split(',')) : []
        setDefaultKeys(allIdRes.flat())
        await getAllRightsData()
        setIsDispatchRoleRightsVisible(true)
    }

    // 确认角色授权
    const handleRoleRights = async () => {
        const { meta } = await setRoleRights(roleID, checkRightsId)
        if(meta.status !== 200) return message.error('角色授权失败')
        message.success('角色授权成功')
        setIsDispatchRoleRightsVisible(false)
        getRolesList()
    }

    // 取消角色授权
    const handleCancelRoleRights = () => {
        setIsDispatchRoleRightsVisible(false)
    }

    // 每列标题
    const columns = [
        {
          title: '#',
          dataIndex: 'index',
          index: 'key',
          width:'100px'
        },
        {
          title: '角色名称',
          dataIndex: 'roleName',
          key: 'roleName'
        },
        {
          title: '角色描述',
          dataIndex: 'roleDesc',
          key: 'roleDesc'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width:'200px',
          render:(_, record) => {
              const component = <Space>
              <Button onClick={() => onEditRole(record)} icon={<EditOutlined />} type="primary">编辑</Button>
              <Button onClick={() => onDeleteRole(record.id)} icon={<DeleteOutlined />} type="danger">删除</Button>
              <Button onClick={() => onSetRoleRight(record)} icon={<SettingFilled />} className="allocate-rights">分配权限</Button>
          </Space>
              return component
          }
        }
      ]
    return (
        <Card className="role-container">
            <Button onClick={addRole} type="primary" size="large">添加角色</Button>
            {/* 角色列表 table */}
            <Table
                bordered
                dataSource={rolesList}
                columns={columns}
                pagination={false}
                expandable={{
                    expandedRowRender,
                    expandIcon
                }}
                rowKey={record => record.id}
                childrenColumnName="noneChildren"
            />
            {/* 添加角色模态框 */}
            <Modal cancelText="取消" okText="确认" title="增加角色" visible={isAddRoleVisible} onOk={handleAddRole} onCancel={handleCancelAddRole}>
            <Form
                name="addrole"
                form={addRoleForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
            >
                <Form.Item
                    label="角色名称"
                    name="roleName"
                    rules={addRoleRules.roleName}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="角色描述"
                    name="roleDesc"
                    rules={addRoleRules.roleDesc}
                >
                    <Input />
                </Form.Item>
            </Form>
            </Modal>
            {/* 编辑角色模态框 */}
            <Modal cancelText="取消" okText="确认" title="编辑角色" visible={isEditRoleVisible} onOk={handleEditRole} onCancel={handleCancelEditRole}>
            <Form
                name="editrole"
                form={editRoleForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                initialValues={{
                    roleName:editRole.roleName,
                    roleDesc:editRole.roleDesc
                }}
            >
                <Form.Item
                    label="角色名称"
                    name="roleName"
                    rules={addRoleRules.roleName}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="角色描述"
                    name="roleDesc"
                    rules={addRoleRules.roleDesc}
                >
                    <Input />
                </Form.Item>
            </Form>
            </Modal>

            {/* 分配权限模态框 */}
            {
                isDispatchRoleRightsVisible && <Modal
                    cancelText="取消"
                    okText="确认"
                    title="分配权限"
                    visible={isDispatchRoleRightsVisible}
                    onOk={handleRoleRights}
                    onCancel={handleCancelRoleRights}
                                               >
                    <Tree
                        checkable
                        defaultExpandAll
                        defaultCheckedKeys={defaultKeys}
                        onCheck={onCheckRoles}
                        treeData={treeAllRightsData}
                    />
               </Modal>
            }
        </Card>
    )
}
